<?php
namespace app\scodetrace\model;

use \think\Model;
/*
	批次模型
*/
class Batch extends \app\common\model\Base{
	protected $table='xl_batch';
	// protected $visible=['name'];

	protected $append=['submitter','create_time_l','is_deleted'];
	protected $insert=['submitter_id','submitter_time'];
	protected $_RejectCreate = ['submitter_time','submitter','last_time'];
  protected $_RejectUpdate = ['submitter_time','submitter','last_time'];
	use \app\common\model\BaseSubmitter;

	public function getCreateTimeLAttr($value,$data) {
		return date('Y-m-d', $data['create_time']);
	}

	public function getLastTimeAttr($value) {
		return date('Y-m-d h:i:s',$value);
	}

	public function getIsDeletedAttr($value,$data) {
		if (isset($data['deleted']) && $data['deleted']) {
			return '已删除';
		} else {
			return '';
		}
	}

	public function logOne($logText,$area,$result) {
		$pid = $this->getAttr('log_id');
		$logModel=model('TraceLog');
		if ($pid) {
			if ($logData=$logModel->where('id',$pid)->find()){
				if ($logText==$logData->getAttr('logtext') && $area==$logData->getAttr('area') && $result == $logData->getAttr('result')) {
					$this->error='请勿反复提交相同的内容';
					return false;
				} else if ($this->getAttr('out_time') != null) {
					$this->error='该批次已经出厂，请到防伪码处写入log';
					return false;
				}
			} else {
				$this->error="批次表已经被损坏";
				return false;
			}
		} else {
			$pid = 0;
		}

		if ($log_id=$logModel::logOne($pid,$logText,$area,$result)) {
			$this->setAttr('log_id',$log_id);
			$this->save();
			return true;
		} else {
			$this->error= '写入log失败';
			return false;
		}
	}

	public function product() {
		return $this->belongsTo("\\app\\baseinfo\\model\\Product",'product_id');
	}

	public function logs(){
		$logModel = model('TraceLog');
		if ($log_id=$this->getAttr('log_id')){
			if ($ids=$logModel->getLogIds($log_id)) {
				return $logModel->select($ids);
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

	protected function _doing_delDataById($delIds){
		if (db($this->table)->where('id', 'in', $delIds)->update(['deleted'=>1])){
			return true;
		}
		return false;
	}


	protected function _after_createData(&$param) {
		$m=$this->get($param['id']);
		$m->last_time = time();
		$m->save();
		return true;
	}

	protected function _after_updateDataById(&$param) {
		$m=$this->get($param['id']);
		$m->last_time = time();
		$m->save();
		return true;
	}

}
?>